<template>
  <div>
    <el-card>
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick" :key="activeName">
        <!-- <el-tab-pane label="系统介绍" name="1">
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="标题">
              <el-input
                v-model="formInline.title"
                placeholder="请输入标题"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="getList()">搜索</el-button>
              <el-button type="info" @click="chongzhi">重置</el-button>
              <el-button type="primary" @click="addfn">新增</el-button>
            </el-form-item>
          </el-form>
          <div>
            <el-table :data="tableData" border style="width: 100%">
              <el-table-column prop="id" label="编号" width="88" align="center">
              </el-table-column>
              <el-table-column
                prop="title"
                label="标题"
                width="180"
                align="center"
              >
              </el-table-column>
              <el-table-column prop="" label="图片" width="180" align="center">
                <template #default="{ row }">
                  <div>
                    <el-image
                      style="width: 100px; height: 100px"
                      :src="row.img"
                      fit="cover"
                    ></el-image>
                  </div>
                </template>
</el-table-column>
<el-table-column prop="des" label="简介" width="226" align="center">
</el-table-column>
<el-table-column prop="remark" label="介绍" width="500" align="center">
</el-table-column>
<el-table-column prop="sort" label="排序" width="100" align="center">
</el-table-column>
<el-table-column prop="createTime" label="创建时间" width="188" align="center">
</el-table-column>
<el-table-column prop="" label="操作" width="188" align="center">
  <template #default="{ row }">
                  <el-button type="text" @click="changefn(row)">修改</el-button>
                  <el-button style="color: red" type="text" @click="delfn(row)"
                    >删除</el-button
                  >
                </template>
</el-table-column>
</el-table>
</div>
<div style="text-align: right; margin-top: 20px">
  <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
    :current-page="formInline.pageNum" :page-sizes="[5, 10, 20, 30, 50]" :page-size="formInline.pageSize"
    layout="total, sizes, prev, pager, next, jumper" :total="total">
  </el-pagination>
</div>
</el-tab-pane> -->
        <el-tab-pane label="合作伙伴" name="2">
          <div style="padding-bottom: 10px;">
            <el-button type="primary" @click="addfn">新增</el-button>
          </div>

          <div style="color: #666;margin-bottom: 10px;">
            最后一条的排序填写总商家数量
          </div>
          <div>
            <el-table :data="tableData" border style="width: 100%">
              <el-table-column prop="id" label="编号" width="88" align="center">
              </el-table-column>
              <el-table-column prop="" label="图片" width="180" align="center">
                <template #default="{ row }">
                  <div>
                    <el-image style="width: 100px; height: 100px" :src="row.img" fit="cover"></el-image>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="title" label="标题" width="100" align="center">
              </el-table-column>
              <el-table-column prop="sort" label="排序" width="100" align="center">
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间" width="188" align="center">
              </el-table-column>
              <el-table-column prop="" label="操作">
                <template #default="{ row }">
                  <el-button type="text" @click="changefn(row)">修改</el-button>
                  <el-button style="color: red" type="text" @click="delfn(row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div style="text-align: right; margin-top: 20px">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
              :current-page="formInline.pageNum" :page-sizes="[5, 10, 20, 30, 50]" :page-size="formInline.pageSize"
              layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
          </div>
        </el-tab-pane>
        <el-tab-pane label="商务列表" name="3">
          <div style="padding-bottom: 10px;">
            <el-button type="primary" @click="addfn">新增</el-button>
          </div>

          <div>
            <el-table :data="tableData" border style="width: 100%">
              <el-table-column prop="id" label="编号" width="88" align="center">
              </el-table-column>
              <el-table-column prop="title" label="名称" align="center">
              </el-table-column>
              <el-table-column prop="" label="二维码" width="180" align="center">
                <template #default="{ row }">
                  <div>
                    <el-image style="width: 100px; height: 100px" :src="row.img" fit="cover"></el-image>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="des" label="手机号" align="center">
              </el-table-column>
              <el-table-column prop="remark" label="微信号" align="center">
              </el-table-column>
              <el-table-column prop="sort" label="排序" width="100" align="center">
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间" width="188" align="center">
              </el-table-column>
              <el-table-column prop="" label="操作">
                <template #default="{ row }">
                  <el-button type="text" @click="changefn(row)">修改</el-button>
                  <el-button style="color: red" type="text" @click="delfn(row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div style="text-align: right; margin-top: 20px">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
              :current-page="formInline.pageNum" :page-sizes="[5, 10, 20, 30, 50]" :page-size="formInline.pageSize"
              layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
          </div>
        </el-tab-pane>

        <el-tab-pane label="功能推荐" name="4">
          <div style="padding-bottom: 10px;">
            <el-button type="primary" @click="addFeatureRecommendation">新增</el-button>
          </div>
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="标题">
              <el-input v-model="formInline.title" placeholder="请输入标题"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="getList()">搜索</el-button>
            </el-form-item>
          </el-form>
          <div>
            <el-table :data="tableData" border style="width: 100%">
              <el-table-column prop="id" label="编号" width="88" align="center">
              </el-table-column>
              <el-table-column prop="title" label="标题" width="180" align="center">
              </el-table-column>
              <el-table-column prop="" label="图片" align="center">
                <template #default="{ row }">
                  <div>
                    <el-image style="width: 100px; height: 100px" :src="row.img" fit="cover"></el-image>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="des" label="简介" align="center">
              </el-table-column>

              <el-table-column prop="jump" label="路径" align="center">
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间" align="center">
              </el-table-column>
              <el-table-column prop="" label="操作" width="188" align="center">
                <template #default="{ row }">
                  <el-button type="text" @click="changefns(row)">修改</el-button>
                  <el-button style="color: red" type="text" @click="delfn(row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div style="text-align: right; margin-top: 20px">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
              :current-page="formInline.pageNum" :page-sizes="[5, 10, 20, 30, 50]" :page-size="formInline.pageSize"
              layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 新增或修改 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="666px" @close="close">
      <el-form :model="form" ref="ruleForm" :rules="rules" label-width="100px">
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option v-for="item in arr" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="title" v-if="form.type == 2 || form.type == 3">
          <el-input style="width: 333px" v-model="form.title" autocomplete="off" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="简介" prop="des" v-if="form.type == 1">
          <el-input style="width: 333px" v-model="form.des" autocomplete="off" placeholder="请输入简介"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="des" v-if="form.type == 3">
          <el-input style="width: 333px" v-model="form.des" autocomplete="off" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="微信号" prop="remark" v-if="form.type == 3">
          <el-input style="width: 333px" v-model="form.remark" autocomplete="off" placeholder="请输入微信号"></el-input>
        </el-form-item>
        <el-form-item label="图片" prop="img">
          <el-upload :class="{ hiddenupload: titleImgList.length }" :action="uploadImgUrl" list-type="picture-card"
            :file-list="titleImgList" :limit="1" accept=".jpg,.jpeg,.png" :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove" :on-success="successhttp">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input style="width: 333px" v-model="form.sort" autocomplete="off" placeholder="请输入排序"></el-input>
        </el-form-item>
        <el-form-item label="介绍" prop="remark" v-if="form.type == 1">
          <el-input type="textarea" :rows="6" style="width: 500px" v-model="form.remark" autocomplete="off"
            placeholder="请输入介绍"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="okSure">确 定</el-button>
      </div>
      <el-dialog title="图片详情" :visible.sync="dialogVisible" append-to-body>
        <img width="100%" :src="dialogImageUrl" alt="" />
      </el-dialog>
    </el-dialog>

    <!-- 功能推荐弹窗 -->
    <el-dialog title="功能推荐" :visible.sync="featureDialogVisible" width="700px" @close="closeFeatureDialog">
      <el-form :model="featureForm" ref="featureRuleForm" :rules="featureRules" label-width="100px">
        <el-form-item label="类型" prop="type">
          <el-select v-model="featureForm.type" placeholder="请选择类型">
            <el-option v-for="item in arr2" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="功能分类" prop="routeId">
          <treeselect v-model="featureForm.routeId" :options="menuOptions" :normalizer="normalizer" :show-count="true"
            placeholder="选择上级菜单" />
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="featureForm.title" placeholder="请输入标题" style="width: 100%"></el-input>
        </el-form-item>

        <el-form-item label="简介" prop="des">
          <el-input type="textarea" :rows="3" v-model="featureForm.des" placeholder="请输入简介"
            style="width: 100%"></el-input>
        </el-form-item>

        <el-form-item label="图片" prop="img">
          <el-upload :class="{ hiddenupload: featureImgList.length }" :action="uploadImgUrl" list-type="picture-card"
            :file-list="featureImgList" :limit="1" accept=".jpg,.jpeg,.png" :on-preview="handleFeaturePicturePreview"
            :on-remove="handleFeatureImageRemove" :on-success="handleFeatureImageSuccess">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>


      </el-form>

      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="featureDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitFeatureRecommendation">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMenu } from "@/api/system/menu";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Treeselect from "@riophae/vue-treeselect";
import { getList, addfnList, detailfnList, editfnList, deletefnList } from '../../../api/IntroductionPartners/index'
export default {
  components: { Treeselect },
  data() {
    return {
      dialogFormVisible: false,
      dialogImageUrl: '',
      dialogVisible: false,
      uploadImgUrl: '',
      titleImgList: [],
      // 功能推荐弹窗相关数据
      featureDialogVisible: false,
      featureImgList: [],
      featureForm: {
        type: '4',
        title: '',
        image: '',
        jump: '',
        permission: '', // 权限字符
        routeId: 0      // 路由参数
      },
      featureRules: {
        type: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        des: [
          { required: true, message: '请输入简介', trigger: 'blur' }
        ],
        img: [
          { required: true, message: '请上传图片', trigger: 'change' }
        ],
        routeId: [
          { required: true, message: '请选择功能分类', trigger: 'change' }
        ]
      },

      menuOptions: [

      ],
      formInline: {
        pageSize: 10,
        pageNum: 1,
        title: null,
        type: '2',
      },
      form: {
        title: null,
        des: null,
        img: null,
        type: '2',
        remark: null,
        sort: null,
      },
      title: '合作伙伴',
      arr: [
        { name: '合作伙伴', id: '2' },
        { name: '商务列表', id: '3' },

      ],
      arr2: [

        { name: '功能推荐', id: '4' },
      ],
      activeName: '2',
      rules: {
        type: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],

        des: [
          { required: true, message: '请输入详情', trigger: 'change' }
        ],
        sort: [
          { required: true, message: '请输入排序', trigger: 'change' }
        ],
        remark: [
          { required: true, message: '请输入介绍', trigger: 'change' }
        ],
        img: [
          { required: true, message: '请上传图片', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请输入标题', trigger: 'change' }
        ],
      },
      tableData: [],
      total: 0
    }
  },
  // computed: {
  //    routeData() {
  //     return this.$store.state.permission.routeData
  //   },
  // },
  created() {

    this.uploadImgUrl = process.env.VUE_APP_BASE_API + "/upload/image";
    this.getList()


  },
  methods: {
    //重置
    chongzhi() {
      this.formInline = {
        pageSize: 10,
        pageNum: 1,
        title: null,
        name: '1'
      }
      this.getList()
    },
    async getList() {
      const res = await getList(this.formInline)
      console.log(res);
      this.tableData = res.rows
      this.total = res.total
    },
    handleClick(tab) {
      if (tab.name == 1) {
        this.title = '系统介绍'
      } else {
        this.title = '合作伙伴'
      }
      this.formInline.pageNum = 1
      this.formInline.pageSize = 10
      this.formInline.type = tab.name
      this.form.type = tab.name

      this.featureForm.type = tab.name
      this.getList()
    },
    // 新增或修改
    addfn() {
      this.dialogFormVisible = true
    },
    okSure() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          //   alert('submit!');
          if (this.form.id) {
            const res = await editfnList(this.form)
            console.log(res);
          } else {
            const res = await addfnList(this.form)
            console.log(res);
          }
          this.getList()
          this.$message.success('操作成功！')
          this.dialogFormVisible = false
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.titleImgList = []
      this.form.img = ''
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    successhttp(response, file, fileList) {
      console.log('333', response, file, fileList);
      this.titleImgList = []
      this.form.img = response.data.filePath
      this.titleImgList.push({ url: response.data.filePath })
    },
    close() {
      this.dialogFormVisible = false
      this.form = {
        title: null,
        des: null,
        img: null,
        type: this.form.type,
        remark: null,
        sort: null
      }
      this.titleImgList = []
      this.title = '系统介绍'
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.formInline.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.formInline.pageNum = val
      this.getList()
    },
    //修改
    async changefn(item) {
      this.dialogFormVisible = true
      const res = await detailfnList(item.id)
      console.log(res);
      this.form = res.data
      if (this.form.img) {
        this.titleImgList.push({ url: this.form.img })
      }
    },
    async changefns(item) {
       // 先加载菜单数据
  await this.getTreeselect();
  
      const res = await detailfnList(item.id)
      this.featureForm = res.data
      this.featureForm.routeId = Number(res.data.routeId)
      if (this.featureForm.img) {
        this.featureImgList.push({ url: this.featureForm.img })
      }
      this.featureDialogVisible = true
    },
    // 删除
    async delfn(item) {
      this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await deletefnList(item.id)
        console.log(res);
        this.$message.success('删除成功！')
        this.getList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 功能推荐相关方法
    addFeatureRecommendation() {
      this.featureDialogVisible = true;
      this.resetFeatureForm();
      this.getTreeselect()
    },

    closeFeatureDialog() {
      this.featureDialogVisible = false;
      this.resetFeatureForm();
    },

    resetFeatureForm() {
      this.featureForm = {
        type: '4',
        title: '',
        des: '',
        img: '',
        permission: '', // 权限字符
        routeId: 0    // 路由参数
      };
      this.featureImgList = [];
      if (this.$refs.featureRuleForm) {
        this.$refs.featureRuleForm.clearValidate();
      }
    },

    handleFeaturePicturePreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    handleFeatureImageRemove(file, fileList) {
      this.featureImgList = [];
      this.featureForm.img = '';
    },

    handleFeatureImageSuccess(response, file, fileList) {
      this.featureImgList = [];
      this.featureForm.img = response.data.filePath;
      this.featureImgList.push({ url: response.data.filePath });
    },

    submitFeatureRecommendation() {
      this.$refs.featureRuleForm.validate(async (valid) => {
        if (valid) {
          try {
            // 获取所有菜单项的扁平列表
            let allMenus = this.flattenMenus(this.menuOptions);

            // 在扁平列表中查找选中的菜单项
            const selectedMenu = allMenus.find(item => item.menuId === this.featureForm.routeId);
            const selectedMenuParent = allMenus.find(item => item.menuId === selectedMenu.parentId);
            console.log(selectedMenuParent, 'selectedMenuParent');

            if ((!selectedMenu || !selectedMenu.path || !selectedMenu.component) && selectedMenu.status !== 1) {
              this.$message.error('请选择正确的功能路由');
              return false;
            }

            // 设置权限字符和路由路径
            this.featureForm.permission = selectedMenu.perms || '';

            // 构建完整路径（父级路径 + 当前路径）
            let fullPath = selectedMenu.path || '';
            console.log(selectedMenu,'selectedMenuselectedMenu')
            // return
            if (selectedMenu &&selectedMenuParent.path ) {
              fullPath = selectedMenuParent.path + '/' + fullPath;
            }
            this.featureForm.jump = fullPath;

            console.log('提交的表单数据:', this.featureForm);

            if (this.featureForm.id) {
              const res = await editfnList(this.featureForm);
              console.log(res);
            } else {
              const res = await addfnList(this.featureForm);
              console.log(res);
            }
            this.getList();
            this.$message.success('操作成功！');
            this.dialogFormVisible = false;
            this.featureDialogVisible = false;
          } catch (error) {
            console.error('提交功能推荐时出错:', error);
            this.$message.error('提交失败，请检查路由参数');
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    // 将菜单树扁平化为一维数组
    flattenMenus(menuOptions) {
      let result = [];

      for (const menu of menuOptions) {
        result.push(menu);

        if (menu.children && menu.children.length) {
          result = result.concat(this.flattenMenus(menu.children));
        }
      }

      return result;
    },

    // 递归查找菜单项
    findMenuById(menuOptions, menuId) {
      // 处理根级菜单
      for (const option of menuOptions) {
        // 检查当前项
        if (option.menuId === menuId) {
          return option;
        }

        // 如果当前项有子项，递归查找
        if (option.children && option.children.length) {
          for (const child of option.children) {
            if (child.menuId === menuId) {
              return child;
            }

            // 继续递归查找更深层次
            if (child.children && child.children.length) {
              const found = this.findMenuById(child.children, menuId);
              if (found) return found;
            }
          }
        }
      }
      return null;
    },

    /** 查询菜单下拉树结构 */
    getTreeselect() {
      listMenu().then(response => {
        this.menuOptions = [];
        const menu = { menuId: 0, menuName: '主类目', children: [] };

        // 处理菜单数据，保留query参数和路径信息
        const processedData = this.processMenuData(response.data);

        menu.children = this.handleTree(processedData, "menuId");
        this.menuOptions.push(menu);
        console.log('菜单选项:', this.menuOptions);
      });
    },

    // 处理菜单数据，添加必要的标记和路径信息
    processMenuData(menuData, parentPath = '') {
      return menuData.map(item => {
        // 保留原始数据中的query参数
        if (item.query) {
          item._hasQuery = true; // 添加标记，表示有query参数
        }

        // 构建完整路径
        item.parentPath = parentPath;
        const currentPath = parentPath ? `${parentPath}/${item.path}` : item.path;

        // 如果有子菜单，递归处理
        if (item.children && item.children.length > 0) {
          item.children = this.processMenuData(item.children, currentPath);
        }

        return item;
      });
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }

      // 构建标签文本，如果有query参数则显示标记
      let labelText = node.menuName;
      if (node.query) {
        labelText = `${node.menuName} [有参数]`;
      }

      return {
        id: node.menuId,
        label: labelText,
        children: node.children,
        query: node.query,     // 保留query参数
        _hasQuery: node._hasQuery, // 保留标记
        perms: node.perms,     // 保留权限字符
        path: node.path,       // 保留路由路径
        parentPath: node.parentPath // 保留父级路径
      };
    },
  }
}
</script>

<style lang="scss" scoped>
::v-deep .hiddenupload .el-upload--picture-card {
  display: none;
}
</style>